define(['jquery','form'], function ($,Form) {

    var util = {
        /**
         * 自定义下拉选择框事件
         * @param element selector|dom|jquery object
         */
        bindSelect: function(element) {
            $(element).each(function() {
                var $this = $(this);
                if($this.data('selector-init')) {
                    return;
                }
                var options = $this.data();
                var $handler = $('.handler', this);//点击触发节点
                var $input = $('input:hidden', this);
                var $options = $('.options', this);
                var $title = options.query ? $(options.query, this) : $handler.children().eq(0);//显示节点
                function setupTitle() {
                    // 根据当前input value设置title
                    var currentValue = $input.val();
                    var text = currentValue==='' ? '' : $options.find('li[value="'+currentValue+'"]').text();
                    if($title.is('input')) {
                        $title.val(text);
                    }else {
                        var textNode = $title.contents().filter(function() {
                            return this.nodeType === Node.TEXT_NODE;
                        });
                        if(textNode.length>0) {
                            textNode[0].data = text;
                        }
                    }
                    if(text) {
                        $title.val(text);
                    }else {
                        $title.val('');
                    }
                }
                function showOptions() {
                    $options.stop().slideDown(100);
                }
                function hideOptions() {
                    $options.stop().slideUp(100);
                }
                $handler.on('click', function () {
                    if($options.is(':visible')) {
                        return;
                    }
                    showOptions();
                    var random = Math.random();
                    setTimeout(function(){
                        $('body').on('click.'+random, function (event) {
                            hideOptions();
                            $('body').off('click.'+random);
                        });
                    },1);
                });
                $('.options li', this).click(function () {
                    var value = $(this).attr('value'), text = $(this).text();
                    $input.val(value).trigger('validate').trigger('change');
                });
                $input.on('change', function() {
                    setupTitle();
                });
                setupTitle();//初始调用一次
                $this.data('selector-init', true);
            });
        },
        /**
         * 调起联动选择， dom启动后再调用
         * @param options object, id:写入input的id; steps:array; callback:function,选择确定后回调;
         */
        cxSelect: function(options) {
            require(['cxselect'], function () {
                var randomId = parseInt(Math.random()*10000);
                var divstr = '<div id="{{id}}" class="form-inline {{class}} " {{style}} data-toggle="cxselect" data-selects="{{selects-name}}">{{selects}}</div>';
                divstr = divstr.bind({
                    'id': randomId,
                    'class': options.class ? options.class : '',
                    'style': options.style ? 'style="'+options.style+'"' : ''
                });

                var selectsName = [], selects = [];
                options.steps.forEach(function(item,index){
                    var select = '<select class="step{{index}} form-control" {{name}} data-url="{{data-url}}" {{extra}}></select>'.bind({
                        'index': index,
                        'name': item.name ? 'name="'+item.name+'"' : '',
                        'data-url': item['data-url'] ? item['data-url'] : '',
                        'extra': item.extra ? item.extra : ''
                    });
                    selectsName.push('step'+index);
                    selects.push(select);
                });
                selectsName = selectsName.join(',');
                selects = selects.join('');
                divstr = divstr.bind({'selects-name': selectsName,'selects': selects});
                layer.confirm(divstr, {title:options.title||'请选择'}, function(index) {
                    var $option = $div.find('select:last option:selected');
                    var value = $option.val(), text = $option.text();
                    if(!value) {
                        return;
                    }
                    if(options.id) {
                        $('#'+options.id).val(value);
                    }
                    if(options.callback) {
                        options.callback(value, text);
                    }
                    Layer.close(index);
                });
                var $div = $('#'+randomId);
                $div.cxSelect({
                    jsonName: 'name',
                    jsonValue: 'value',
                    jsonSpace: 'data',
                });
            });
        },
        /**
         * 使用iframe弹窗打开页面
         * options.area 宽高 ["100px","200px"]
         */
        openLayerFrame: function(url, options) {
            options = $.extend({
                type:2, content: Fast.api.fixurl(url), title: '', shadeClose:true, resize:false, closeBtn:0, area: 'auto', id: ''
            }, options);
            Layer.open(options);
        },
        /**
         * 关闭当前layer frame, 在iframe中调用
         */
        closeLayerFrame: function () {
            try {
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index); //再执行关闭
            }catch (e) {
                console.error(e);
            }
        },
        /**
         * ajax获取列表数据，分页数据
         */
        ajaxFetch: function (listId,paginatorId, fetchUrl) {
            var $list = $(listId), $paginator = $(paginatorId);
            //data需要有view(视图) paginator(分页)两个参数
            var successCall = function(data,ret) {
                $list.empty().append(data.view);
                $paginator.empty().append(data.paginator);
                $paginator.find('form').on('submit', function (event) {
                    event.preventDefault();
                    var data = $(this).serialize();
                    Fast.api.ajax({url:fetchUrl,data:data},successCall);
                });
                return false;
            };
            Fast.api.ajax({url:fetchUrl},successCall);
            $paginator.on('click', 'a', function (event) {
                event.preventDefault();
                var url = $(this).attr('href');
                if(url) {
                    Fast.api.ajax({url:url}, successCall);
                }
            });
        },
        getGeoLocation: function (success, fail) {
            require(['qq-geo'], function () {
                var geolocation = new qq.maps.Geolocation("5VDBZ-AGI6F-QLSJL-NIGEB-KXZ2F-YLFDB", "贤聘网");
                geolocation.getLocation(function(position){
                    // var adCode = position.adCode;//邮政编码
                    // var nation = position.nation;//中国
                    // var city = position.city; //城市
                    // var addr = position.addr; //详细地址
                    // var lat = position.lat; //
                    // var lng = position.lng; //火星坐标
                    success(position);
                }, function () {
                    // Toastr.error('定位失败');
                    if(typeof fail==='function')
                        fail.call(this, arguments);
                }, {timeout: 5000});
            })
        },
        download: function (url) {
            var iframe = document.createElement("iframe");
            iframe.style.display = "none"; // 防止影响页面
            iframe.style.height = 0; // 防止影响页面
            iframe.src = url;
            document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
            // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
            setTimeout(function() {
                iframe.remove();
            }, 5 * 60 * 1000);

        },
        // 判定是否可以进行简历相关操作
        actionVerify: function (resume_id,cb) {
            Fast.api.ajax({
                url: Fast.api.fixurl('xilujob.user/action_msg'),
                data:{resume_id:resume_id}
            },function () {
                if(typeof cb=='function') cb();
                return false;
            }, function (data, ret) {
                Layer.confirm(data.msg, {
                    btn: ['联系升级','稍后再说']
                },function (index) {
                    window.open("http://wpa.qq.com/msgrd?v=3&uin={{qq}}&site=qq&menu=yes".bind({qq:Config.site.pc_qq_service}));
                    Layer.close(index);
                });
                return false;
            });

            return false;
        },
    };
    return util;

});